package com.my.socket.nio.v2;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by ZhongGang
 * at 2018/6/29 15:22
 */
public class Server {
    private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);

    private Selector acceptSelector;
    private Selector readSelector;

    private ServerSocketChannel serverSocketChannel;

    public Server(String host, int port) {
        try {
            this.acceptSelector = Selector.open();
            this.readSelector = Selector.open();

            this.serverSocketChannel = ServerSocketChannel.open();
            this.serverSocketChannel.configureBlocking(false);
            InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
            this.serverSocketChannel.bind(inetSocketAddress);
            this.serverSocketChannel.register(this.acceptSelector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            LOGGER.error("exception caught, the error is {}", e.getMessage());
            return;
        }
    }

    public void startup() {
        while (true) {
            try {
                this.acceptSelector.select();

                Set<SelectionKey> selectionKeys = this.acceptSelector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    LOGGER.info("incoming socket: {}", socketChannel);
                    socketChannel.configureBlocking(false);
                    socketChannel.register(this.readSelector, SelectionKey.OP_READ, socketChannel);
                    iterator.remove();
                }
            } catch (Exception e) {
                LOGGER.error("exception caught, the error is {}", e.getMessage());
                break;
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Server server = new Server("127.0.0.1", 9999);
        server.startup();
    }
}
